package com.lej.preview

import android.content.Context
import android.content.res.Resources
import android.util.TypedValue
import java.lang.Exception

object ScreenUtil {
    private const val FIELD_NAME = "status_bar_height"
    var statusbarheight = 0
    fun getStatusBarHeight(context: Context): Int {
        if (statusbarheight == 0) {
            runCatching {
                val resId = context.resources.getIdentifier(FIELD_NAME, "dimen", "android")
                if (resId > 0) statusbarheight = context.resources.getDimensionPixelSize(resId)
            }
        }
        if (statusbarheight == 0) {
            try {
                val c = Class.forName("com.android.internal.R\$dimen")
                val o = c.newInstance()
                val field = c.getField(FIELD_NAME)
                val x = field[o] as Int
                statusbarheight = context.resources.getDimensionPixelSize(x)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        if (statusbarheight == 0) {
            statusbarheight = 25.dp
        }
        return statusbarheight
    }

    val Int.dp: Int
        get() {
            return TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP,
                this.toFloat(),
                Resources.getSystem().displayMetrics
            ).toInt()
        }
}